package com.meida.module.bus.provider.controller;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.log.StaticLog;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.meida.common.mybatis.entity.EntityMap;
import com.meida.common.mybatis.model.ResultBody;
import com.meida.common.mybatis.query.CriteriaUpdate;
import com.meida.common.springmvc.base.BaseController;
import com.meida.module.bus.client.entity.*;
import com.meida.module.bus.client.entity.srmapi.basedata.SrmContractsmatdtl;
import com.meida.module.bus.provider.api.util.ApiConstants;
import com.meida.module.bus.provider.api.util.PmsApiUtil;
import com.meida.module.bus.provider.api.util.PmsToolUtil;
import com.meida.module.bus.provider.service.BusMaterialPackage200Service;
import com.meida.module.bus.provider.service.BusMaterialService;
import com.meida.module.bus.provider.service.BusMaterialSrmSubService;
import com.meida.module.bus.provider.service.srmservice.SrmSqlserCommonService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 200分包控制器
 *
 * @author flyme
 * @date 2020-10-29
 */
@RestController
@RequestMapping("/bus/bmp200/")
public class BusMaterialPackage200Controller extends BaseController<BusMaterialPackage200Service, BusMaterialPackage200> {
    @Autowired
    private BusMaterialSrmSubService srmSubService;
    @Autowired
    private SrmSqlserCommonService commonService;
    @Autowired
    private BusMaterialService busMaterialService;
    @Autowired
    private PmsApiUtil pmsApiUtil;

    @ApiOperation(value = "200分包-分页列表", notes = "200分包分页列表")
    @GetMapping(value = "page")
    public ResultBody pageList(@RequestParam(required = false) Map params) {
        return bizService.pageList(params);
    }

    @ApiOperation(value = "200分包-分页列表", notes = "200分包分页列表")
    @GetMapping(value = "common/page")
    public ResultBody pageList1(@RequestParam(required = false) Map params) {
        return bizService.pageList(params);
    }

    @ApiOperation(value = "200分包-列表", notes = "200分包列表")
    @GetMapping(value = "list")
    public ResultBody list(@RequestParam(required = false) Map params) {
        return bizService.listEntityMap(params);
    }

    @ApiOperation(value = "200分包-添加", notes = "添加200分包")
    @PostMapping(value = "save")
    public ResultBody save(@RequestParam(required = false) Map params) {
        return bizService.add(params);
    }

    @ApiOperation(value = "200分包-更新", notes = "更新200分包")
    @PostMapping(value = "update")
    public ResultBody update(@RequestParam(required = false) Map params) {
        return bizService.edit(params);
    }

    @ApiOperation(value = "200分包-删除", notes = "删除200分包")
    @PostMapping(value = "remove")
    public ResultBody remove(@RequestParam(required = false) Map params) {
        return bizService.delete(params);
    }


    @ApiOperation(value = "200分包-详情", notes = "200分包详情")
    @GetMapping(value = "get")
    public ResultBody get(@RequestParam(required = false) Map params) {
        return bizService.get(params);
    }

    @ApiOperation(value = "200分包-修正", notes = "200分包-修正")
    @PostMapping(value = "copyAndUpdate")
    public ResultBody copyAndUpdate(@RequestParam(required = false) Map params) {
        return bizService.copyAndUpdate(params);
    }

    @ApiOperation(value = "200分包-合并", notes = "200分包-合并")
    @PostMapping(value = "merge200")
    public ResultBody merge100(@RequestParam(required = false) Map params) throws Exception {
        return bizService.subMerge200OaCheck(params);
    }

    @ApiOperation(value = "200分包-分承包合同下达", notes = "200分包-分承包合同下达")
    @PostMapping(value = "getSrmPms05Req")
    public ResultBody getSrmPms05Req(@RequestParam(required = false) Map params) throws Exception {
        return bizService.getSrmPms05Req(params);
    }

    @ApiOperation(value = "200分包-导出模板", notes = "200分包-导出模板")
    @PostMapping(value = "export200Template")
    public void exportTemplate(HttpServletRequest request, HttpServletResponse response, @RequestParam(required = false) Map params) {
        bizService.export(params, request, response, "200分包模板表", "200分包模板表", "busMaterialPackage200ExportHandler");
    }

    @ApiOperation(value = "200分包-导入数据", notes = "100分包-导入数据")
    @PostMapping(value = "import200UpdateData")
    public ResultBody import100UpdateData(@RequestParam(required = false) Map params, @RequestParam("file") MultipartFile file) {
        ResultBody resultBody = bizService.importOnUpdateBusMaterialPackage200Data(file, params);
        return resultBody;
    }

    @ApiOperation(value = "200分包-导入数据", notes = "200分包-导入数据")
    @PostMapping(value = "import200AddData")
    public ResultBody import200AddData(@RequestParam(required = false) Map params, @RequestParam("file") MultipartFile file) {
        ResultBody resultBody = bizService.importOnAddBusMaterialPackage200Data(file, params);
        return resultBody;
    }

    @ApiOperation(value = "200分包-获取历史版本", notes = "200分包-获取历史版本")
    @GetMapping(value = "selectVersionList")
    public ResultBody selectVersionList(@RequestParam(required = false) Map params) {
        List<EntityMap> entityMapList = bizService.selectVersionList(params);
        return ResultBody.ok().data(entityMapList);
    }

    @ApiOperation(value = "200分包-SRM系统价格同步", notes = "200分包-SRM系统价格同步")
    @PostMapping(value = "syncSrmPrice")
    public ResultBody syncSrmPrice(@RequestParam(required = true) Long projectId) {
        //【SRM分包价格】同步到PMS母表的【预算成本单价_未税_安装价格】
        //->重新计算
        // 【预算成本单价_未税_综合单价】、
        //【预算成本合价_未税_安装价】、
        //【预算成本合价_未税_合计】

        Map<String, Object> searchMap = Maps.newHashMap();
        searchMap.put(ApiConstants.MAP_PROJECTID, projectId);
        searchMap.put(ApiConstants.MAP_PARENTID, 0);
        Collection<BusMaterialPackage200> busMaterialPackage200s = bizService.listByMap(searchMap);
        if(0 == busMaterialPackage200s.size()) {
            searchMap = Maps.newHashMap();
            searchMap.put(ApiConstants.MAP_PROJECTID, projectId);
            busMaterialPackage200s = bizService.listByMap(searchMap);
        }
        if (0 != busMaterialPackage200s.size()) {
            List<BusMaterialSrmSub> srmSubsList = pmsApiUtil.getBusMaterialSrmSubsByProjectId(projectId, ApiConstants.FB_PLANDATA);

            // key 分包计划主key value
            Map<Long, BusMaterialSrmSub> syncIdSrmSubMap = Maps.newHashMap();
            Map<Long, Long> syncIdMap = Maps.newHashMap();
            List<Long> syncIdList = Lists.newArrayList();
            //  200版本的所有【分包】父级节点数据，
            busMaterialPackage200s.stream().forEach(package200Obj -> {
                if (srmSubsList.stream().anyMatch(srmSubOject -> srmSubOject.getMaterialPackageId().equals(package200Obj.getMaterialPackage100Id()))) {
                    // 200分包计划
                    syncIdMap.put(package200Obj.getMaterialPackage100Id(), package200Obj.getMaterialId());
                    syncIdList.add(package200Obj.getMaterialPackage100Id());
                    syncIdSrmSubMap.put(package200Obj.getMaterialPackage100Id(), srmSubsList.stream().filter(srmSubOject -> srmSubOject.getMaterialPackageId().equals(package200Obj.getMaterialPackage100Id())).findFirst().get());
                } else if (srmSubsList.stream().anyMatch(srmSubOject -> srmSubOject.getMaterialPackageId().equals(package200Obj.getPackagePlan100Id()))) {
                    // 100分包计划
                    syncIdMap.put(package200Obj.getPackagePlan100Id(), package200Obj.getMaterialId());
                    syncIdList.add(package200Obj.getPackagePlan100Id());
                    syncIdSrmSubMap.put(package200Obj.getPackagePlan100Id(), srmSubsList.stream().filter(srmSubOject -> srmSubOject.getMaterialPackageId().equals(package200Obj.getPackagePlan100Id())).findFirst().get());
                }
//                //  1：有对应的100版本数据
//                if (PmsToolUtil.checkLong(package200Obj.getPackagePlan100Id())) {
//                    syncIdMap.put(package200Obj.getPackagePlan100Id(), package200Obj.getMaterialId());
//                    syncIdList.add(package200Obj.getPackagePlan100Id());
//                } else {
//                    //  2：无对应的100版本数据
//                    syncIdMap.put(package200Obj.getPackagePlan100Id(), 0L);
//                    syncIdList.add(package200Obj.getPackagePlan100Id());
//                }
            });
            StaticLog.info("syncIdList：" + syncIdList );
            StaticLog.info("syncIdList：" + syncIdList );
            StaticLog.info("syncIdList：" + syncIdList );
            // key 计划ID value 平均价格
            Map<Long, BigDecimal> syncPriceMap = Maps.newHashMap();
            List<Long> sycnPricePalnIds = Lists.newArrayList();
            //  获取100、200版本对应的SRM关联表数据。
            if (0 < syncIdList.size()) {
                syncIdList.stream().forEach(syncId -> {
                    Map<String, Object> filterMap = Maps.newHashMap();
                    filterMap.put(ApiConstants.MAP_MATERIALPACKAGEID, syncId);
                    if(syncId.equals(1364907098000883717L)) {
                        System.out.println(123);
                    }
                    Collection<BusMaterialSrmSub> srmSubs = srmSubService.listByMap(filterMap);
                    // 一行PMS计划明细，可以对应多条SRM分包明细
                    if (0 < srmSubs.size()) {
                        List<Long> contractDetailIds = Lists.newArrayList();
                        // 读取对应采购明细id，对应的价格数据。
                        srmSubs.stream().forEach(srmSubObj -> {
                            contractDetailIds.add(srmSubObj.getContractsmatdtlId());
                        });
                        List<Long> srmContractsDetailIds = contractDetailIds.stream().distinct().collect(Collectors.toList());
                        Long[] srmDetailIdsArray = srmContractsDetailIds.toArray(new Long[0]);
                        List<SrmContractsmatdtl> srmContractsmatdtls = commonService.getSrmContractsmatdtlByIds(srmDetailIdsArray);
                        BigDecimal contSum = BigDecimal.ZERO;
                        BigDecimal amountSum = BigDecimal.ZERO;
                        if (0 < srmContractsmatdtls.size()) {
                            for (SrmContractsmatdtl contractsmatdtl : srmContractsmatdtls) {
                                contSum = NumberUtil.add(contractsmatdtl.getPmsCount(), contSum);
                                amountSum = NumberUtil.add(NumberUtil.mul(contractsmatdtl.getPmsCount(),contractsmatdtl.getPmsPrice()), amountSum);
                            }
                            if (!BigDecimal.ZERO.equals(contSum)) {
                                syncPriceMap.put(syncId, NumberUtil.div(amountSum, contSum));
                                sycnPricePalnIds.add(syncId);
                            }
                        }
                    }
                });
                if (0 < sycnPricePalnIds.size()) {
                    List<BusMaterial> busMaterials = Lists.newArrayList();
                    sycnPricePalnIds.stream().forEach(syncId -> {
                        BusMaterialPackage200 busMaterialPackage200 = null;
//                        //  1：有对应的100版本数据
//                        if (0L != syncIdMap.get(syncId)) {
                            busMaterialPackage200 = bizService.getById(syncIdMap.get(syncId));
//                        } else {
//                            //  2：无对应的100版本数据
//                            busMaterialPackage200 = bizService.getById(syncId);
//                        }
                        BusMaterial busMaterial = busMaterialService.getById(busMaterialPackage200.getMaterialId());
                        //->重新计算
                        // 预算成本单价_未税_主材价】
                        busMaterial.setInstallPrice(syncPriceMap.get(syncId));
                        // 预算成本单价_未税_综合单价】
                        busMaterial.setSyntheticalPrice(syncPriceMap.get(syncId));

                        //【预算成本合价_未税_主材价】
                        busMaterial.setInstallAmount(NumberUtil.mul(syncPriceMap.get(syncId), busMaterialPackage200.getCostQuantity200()));
                        //【预算成本合价_未税_合计】
                        busMaterial.setSyntheticalAmount(NumberUtil.mul(syncPriceMap.get(syncId), busMaterialPackage200.getCostQuantity200()));
                        busMaterials.add(busMaterial);
                    });
                    if (0 < busMaterials.size()) {
                        //  反写会母表价格
                        busMaterialService.updateBatchById(busMaterials);
                    }
                }
            }
        }
        return ResultBody.ok();
    }

    @ApiOperation(value = "判断材料行是否存在变更中待审核的数据", notes = "判断材料行是否存在变更中待审核的数据")
    @GetMapping(value = "checkUnderReview")
    public ResultBody checkHasUnderReviewRecord(@RequestParam Long materialPackage100Id) {
        CriteriaUpdate<BusMaterialPackage200> cu = new CriteriaUpdate();
        cu.eq("parentId", materialPackage100Id);
        cu.eq("applayStatus", 1);//审批中
        int count = bizService.count(cu);
        if(count > 0) {
            return ResultBody.ok().data("Y");
        }
        return ResultBody.ok().data("N");
    }

}
